<template>
  <div>
    <!-- 查询参数及按钮部分 -->
    
    <!-- 表格部分 -->
    <el-table
      ref="singalTable"
      v-loading="listLoading"
      :data="list"
      :stripe="true"
      fit
      :height="tableHeight"
      :header-cell-style="{background:'#eef1f6',color:'#606266'}"
      :summary-method="getSummaries"
      show-summary
      @selection-change="handleSelectionChange"
    >
      <template slot="empty">
        <tableEmpty />
      </template>
      <el-table-column
        type="selection"
        width="55"
        align="center"
      />
      <el-table-column
        label="序号"
        type="index"
        align="center"
        width="80"
      />
      <el-table-column
        label="工资年度"
        align="center"
        width="110"
        prop="year"
      />
      <el-table-column
        label="单位编码"
        align="center"
        width="110"
        prop="agency_code"
      />
      <el-table-column
        label="单位名称"
        align="center"
        prop="agency_name"
      />
      <el-table-column
        label="发放人数"
        align="center"
        prop='personCount'
      />
      <el-table-column
        label="实发工资总额"
        align="center"
        prop="s1"
      >
        <template slot-scope="{row}">
          <span style="float: right">{{ Number(row.s1).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,") }}</span>
        </template>
      </el-table-column>
  
      
    </el-table>
    <!-- 分页   -->
    <pagination
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />
    <!-- 单位上报情况查询 -->
    <el-dialog  v-dialogDrag  
      title="单位上报情况"
      :visible.sync="unitReportVisible"
      style="padding:0px"
      width="70%"
    >

      <el-tabs
        v-model="unitReportState"
        class="dialog-Backgroundcolor"
      >
        <el-tab-pane
          label="已上报"
          style="margin-left:4%"
          name="1"
        >
          <el-table
            ref="unitReportTable"
            v-loading="unitReportListLoading"
            :data="unitReportList"
            :stripe="true"
            fit
            height="455px"
            max-height="455px"
            :header-cell-style="{background:'#eef1f6',color:'#606266'}"
          >
            <template slot="empty">
              <tableEmpty />
            </template>
            <el-table-column
              type="index"
              width="50"
              label="序号"
            />
            <el-table-column
              label="单位编码"
              align="center"
               prop="agencyCode"
           />
            <el-table-column
              label="单位名称"
              align="center"
              prop="agencyName"
            />
          </el-table>
          <pagination
            :total="unitReportTotal"
            :page.sync="unitReportListQuery.page"
            :limit.sync="unitReportListQuery.limit"
            @pagination="getUnitReportList"
          />
        </el-tab-pane>
        <el-tab-pane
          label="未上报"
          style="margin-left:4%"
          name="0"
        >
          <el-table
            ref="unitReportTable"
            v-loading="unitReportListLoading"
            :data="unitReportList"
            :stripe="true"
            fit
            height="455px"
            max-height="455px"
            :header-cell-style="{background:'#eef1f6',color:'#606266'}"
          >
            <template slot="empty">
              <tableEmpty />
            </template>
             <!-- <el-table-column type="selection" width="30" align="center" /> -->
            <el-table-column
              type="index"
              width="50"
              label="序号"
            />
            <el-table-column
              label="单位编码"
              align="center"
              prop="agencyCode"
            />
            <el-table-column
              label="单位名称"
              align="center"
              prop="agencyName"
            />
          </el-table>
          <pagination
            :total="unitReportTotal"
            :page.sync="unitReportListQuery.page"
            :limit.sync="unitReportListQuery.limit"
            @pagination="getUnitReportList"
          />
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
    <el-dialog  v-dialogDrag  
      title="审核说明"
      :visible.sync="auditFormVisible"
      width="30%"
      max-height="500px"
    >
      <el-form
        ref="auditForm"
        :model="formData"
        label-position="right"
        label-width="120px"
        size="small"
      >
        <el-row>
          <el-col>
            <el-input
              v-model="formData.auditExplain"
              type="textarea"
              :rows="4"
              maxlength="100"
              show-word-limit
            />
          </el-col>
        </el-row>
        <el-row>
          <el-col
            :span="16"
            style="text-align: right; margin-top:5%"
          >
            <el-button
              type="primary"
              :loading="saveExplainLoading"
              @click="saveExplain"
            >
              确定
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>
    <!--审核日志 -->
    <ApprovalProcess ref="app" />

  </div>
</template>
<script>
import {
  getSalaryList,
  queryUnitReportPage
} from '@/api/thirteen/financialVerify'
import { doWorkFlow, rejectWorkFlow ,backWorkFlow } from "@/api/thirteen/workFlow"
// 分页
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import tableEmpty from '@/components/table/empty'
import ApprovalProcess from '@/components/ApprovalProcess/ApprovalProcessThirteen'


export default {
  name: 'Unit',
  components: { ApprovalProcess, Pagination, tableEmpty  },
  filters: {
    isMonthEndFilter(type) {
      if (type === '0') {
        return '未月结'
      } else if (type === '1') {
        return '已月结'
      }
    },
    isSalarySubmitFilter(state) {
      if (state === '0') {
        return '未上报'
      } else if (state === '-1') {
        return '被退回'
      } else if (state === '-9') {
        return '未上报'
      } else if (state === '1') {
        return '已上报'
      }
    },
    isAutoSubmitFilter(state) {
      if (state === '0') {
        return '否'
      }
      if (state === '1') {
        return '是'
      }
      if (state === '2') {
        return '是（有变动）'
      }
    }
  },
  props: ['tabPane'],
  data() {
    return {
      ifShow: false,
      ifShow2: false,
      formInline: {
        is_auto: ''
      },
      tableHeight: null,
      unitReportVisible: false,
      unitReportVisibles: false,
      unitReportState: '1',
      unitReportListLoading: false,
      autoSubmitLoading: false,
      unitReportList: [],
      unitReportTotal: 0,
      unitReportListQuery: {
        page: 1,
        limit: 200,
        menuId: this.$router.currentRoute.meta.menuid,
        menuName:this.$router.currentRoute.meta.menuname
      },
      dialogStatus: '',
      dialogEditFormVisible: false,
      that: this,
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 500,
        flag: '0',
        agencyId: '0',
        menuId: this.$router.currentRoute.meta.menuid,
        menuName:this.$router.currentRoute.meta.menuname
      },
      formData: {
        id: '',
        agencyCode: '',
        agencyName: '',
        sfgzze: '',
        yfgzze: '',
        remark: '',
        auditExplain: '' // 审核说明
      },
      salarys: [],
      saveExplainLoading: false,
      auditFormVisible: false,
      tmp_unitReportList: [],
      selected_list: []
    }
  },
  watch: {
    unitReportState() {
      this.getUnitReportList()
    },
    // 表格的数据数组
    list(val) {
      this.doLayout()
    }
  },
  mounted() {
    this.getTbHeight()
  },
  beforeMount() {
    window.addEventListener('resize', this.getTbHeight)
  },
  // 加载后运行
  created() {
    // 获取参数
    this.listQuery.flag = this.tabPane
    // 加载获取全部数据
    this.getList()
  },
  methods: {
   
    // 退回
    auditReject() {
      const selection = this.$refs.singalTable.selection
      if (selection.length === 0) {
        this.$message({
          message: '请选择要退回的单位',
          type: 'warning',
          showClose: true,
          duration: 4000
        })
        return
      }
      this.formData = Object.assign({}, this.formData, '')
      this.formData.auditExplain = '不同意'
      this.auditFormVisible = true
    },
    // 统一保存
    saveExplain() {
      this.saveExplainLoading = true
      this.sendBack()
    },
    // 获取table高度的方法
    getTbHeight() {
      this.tableHeight = window.innerHeight - 260
    },
    /* 重新渲染table组件 */
    doLayout() {
      this.$nextTick(() => {
        this.$refs.singalTable.doLayout()
      })
    },
    handleEdit() {
      this.dialogStatus = '单位基本信息'
      this.dialogEditFormVisible = true
      this.formData = Object.assign({}, this.formData)
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 审核日志
    processnode() {
      const selection = this.$refs.singalTable.selection
      if (selection.length !== 1 || selection.length == 0) {
        this.$message({
          showClose: true,
          message: '请选择一条数据',
          type: 'warning',
          duration: 4000
        })
        return
      }
      if (!selection[0].agency_id) {
        selection.splice(0, 1)
      }
      this.$refs.app.getList(selection[0].agency_id)
    },
    getList() {
      this.listLoading = true
      getSalaryList(this.listQuery).then(response => {
        this.list = response.data.rows
        this.total = response.data.total
        this.listLoading = false
      })
    },

    // 更新
    handleFilter() {
      this.getList()
    },
    // 确认
    handleConfirm() {
      const selection = this.$refs.singalTable.selection
      if (selection.length === 0) {
        this.$message({
          showClose: true,
          message: '请选择数据',
          type: 'warning',
          duration: 4000
        })
        this.$emit('handleCallback')
        return
      }
      const data = {}
      data['agencyVerifyList'] = selection
      data['menuId'] = this.$router.currentRoute.meta.menuid
      data['menuName'] = this.listQuery.menuName
      doWorkFlow(data).then(response => {
        this.dialogFormVisible = false
        this.$message({
          showClose: true,
          message: '接收成功',
          type: 'success',
          duration: 4000
        })
        this.$emit('handleCallback')
        // 更新
        this.handleFilter()
      })

    },
    // 树方法
    handleTree(data) {
      this.listQuery.agencyId = data.id
      this.getList()
    },
    // 撤销
    undoConfirm() {
      const selection = this.$refs.singalTable.selection
      if (selection.length === 0) {
        this.$message({
          showClose: true,
          message: '请选择数据',
          type: 'warning',
          duration: 4000
        })
        this.$emit('ConfirmCallBack')
        return
      }        
        const data = {}
        data['agencyVerifyList'] = selection
        data['menuId'] = this.$router.currentRoute.meta.menuid
        data['menuName'] = this.listQuery.menuName
        rejectWorkFlow(data).then(response => {
          this.dialogFormVisible = false
          this.$message({
            showClose: true,
            message: '撤销成功',
            type: 'success',
            duration: 4000
          })
          this.$emit('ConfirmCallBack')
          // 更新
          this.handleFilter()
          // })
        })
          .catch(() => {
            this.$emit('ConfirmCallBack')
          })
      
    },
    // 退回
    sendBack() {
      const selection = this.$refs.singalTable.selection
      if (selection.length === 0) {
        this.$message({
          showClose: true,
          message: '请选择数据',
          type: 'warning',
          duration: 4000
        })
        this.$emit('BackCallBack')
        return
      }
      if(this.formData.auditExplain == ''){
          this.$message({
          showClose: true,
          message: '请填写退回原因！',
          type: 'warning',
          duration: 2000
        })
          this.$emit('BackCallBack')
          return
        }
      const data = {}
      data['agencyVerifyList'] = selection
      data['menuId'] = this.$router.currentRoute.meta.menuid
      data['auditExplain'] = this.formData.auditExplain
      data['params'] = this.$route.meta.pageUrl
      data['menuName'] = this.listQuery.menuName
      backWorkFlow(data).then(response => {
        this.dialogFormVisible = false
        this.$message({
          showClose: true,
          message: '退回成功',
          type: 'success',
          duration: 4000
        })
        this.auditFormVisible = false
        this.saveExplainLoading = false
        this.$emit('BackCallBack')
        // 更新
        this.handleFilter()
        // })
      })
        .catch(() => {
          this.$emit('BackCallBack')
        })
    },
    // 单位上报情况查询
    unitReportQuery() {
      this.unitReportVisible = true
      this.unitReportListLoading = true
      this.handleUnitReportFilter()
    },

    handleUnitReportFilter() {
      this.unitReportListQuery.page = 1
      this.unitReportListQuery.limit = 200
      this.getUnitReportList()
    },

    getUnitReportList() {
      this.unitReportListLoading = true
      this.unitReportList = []
      // this.unitReportTotal = 0
      this.unitReportListQuery.flag = this.unitReportState
      queryUnitReportPage(this.unitReportListQuery).then(res => {
        this.unitReportList = res.data.rows
        this.tmp_unitReportList = JSON.parse(JSON.stringify(this.unitReportList))
        this.unitReportTotal = res.data.total
        this.unitReportListLoading = false
      }).catch(() => {
        this.unitReportList = []
        this.unitReportTotal = 0
        this.unitReportListLoading = false
      })
    },
     // 获取勾选的数据data
    handleSelectionChange(val) {
        this.selected_list = val;
      
      },
    //自定义合计
    getSummaries(param) {    
        const { columns, data } = param;      
        const sums = [];
        columns.forEach((column, index) => {
          if (index === 1) {
            sums[index] = '合计';
            return;
          }
          if (index <5) {
            return;
          }
          let values;
          values = data.map(item => Number(item[column.property])); // 无勾选
          if (this.selected_list && this.selected_list.length > 0) { // 有勾选
          values = this.selected_list.map(item => Number(item[column.property]));
            }
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
            if(index>=5){
              if(index==5){
                sums[index]= Number(sums[index]).toFixed(0).replace(/(\d)(?=(\d{3})+\.)/g, "$1,")
                sums[index] += ' 人';
              }else{
                sums[index]= Number(sums[index]).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,")
                sums[index] += ' 元';
              }
               
            }
          } else {
            sums[index] = '';
          }
        });
    
        return sums;
      }
  }
}
</script>
<style scoped lang="scss">
@import "~@/styles/border.scss"; /*引入公共样式*/
// ::v-deep tbody > tr:nth-child(1) {
//   .el-checkbox {
//     display: none;
//   }
// }
</style>
